const { Add, Update, QueryOne, Exec_Count, Exec, Query, ExecGetOne } = require('../db/dbhelper');
var { init, format } = require('../models/order');
var { formatDateYear, formatDateTime, MathCode, formatDate } = require('../libs/common');
var _ = require('underscore');
var { sendMsg } = require('./wechat');
var { exportParse } = require('../libs/xlsx');
const logger = require('../libs/log').logger;
const { activeDone, signSendUser, signSendSelfUser} = require('../services/dailyuser');
const { decodeData, refunds } = require('../libs/wxpay');
var moment = require('moment');

// 创建订单
async function orderAdd(doc) {
  try {
    let isdone = await QueryOne('hzz_orders', { pcode: doc.pcode, title: doc.title });
    if (isdone && isdone.paystatus != 9) {
      if (isdone.paystatus == 1) {
        return {
          code: 1,
          msg: '您已经报过名了，无需再次报名!'
        }
      } else {
        return {
          code: 0,
          ordercode: isdone.ordercode,
          msg: '您已下单，请完成支付即可参加活动!'
        }
      }
    } else {
      logger.info('orderAdd--,', doc);
      await Add('hzz_orders', init(doc));
      return {
        code: 0,
        msg: '订单已生成',
        ordercode: doc.ordercode
      }
    }
  } catch (error) {
    logger.error('-----orderAdd----生成订单异常,请联系客服,error', error)
    return {
      code: 1,
      msg: '生成订单异常,请联系客服'
    }
  }
}
// 订单列表
async function orderList(doc) {
  try {
    logger.info('orderList---', doc)
    let { pagenum, pagesize, pcode, Filter } = doc;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    let sql = `SELECT * FROM hzz_orders Where 1=1 `;
    if (pcode) {
      sql += ` AND pcode ='${pcode}'`;
    }
    let ffter = '';
    if (Filter) {
      let fter = ' where 1=1 ';
      let { name, gender, level, auditstatus, paystatus, signstatus, invitecode, activeid } = Filter;
      if (name) {
        fter += ` AND (nickname like '%${name}%' or name like '%${name}%' or name_father like '%${name}%')`;
      }
      if (gender) {
        fter += ` AND grender = '${gender}'`;
      }
      if (level) {
        fter += ` AND level=${level}`;
      }
      let peol = await Exec(`select code from hzz_peoples ` + fter);
      let pcodel = _.uniq(_.compact(_.pluck(peol, 'code')));
      if (pcodel && pcodel.length) {
        ffter += ` AND pcode IN(${pcodel.join(',')})`
      }
      if ((auditstatus || auditstatus == 0) && auditstatus != '') {
        ffter += ` AND auditstatus=${auditstatus}`;
      }
      if ((paystatus || paystatus == 0) && paystatus != '') {
        ffter += ` AND paystatus=${paystatus}`;
      }
      if ((signstatus || signstatus == 0) && signstatus != '') {
        ffter += ` AND signstatus=${signstatus}`;
      }
      if (activeid) {
        ffter += ` AND activeid=${activeid}`;
      }
      if (invitecode) {
        ffter += ` AND invitecode=${invitecode}`;
      }
    }
    sql += ffter;
    sql += ' ORDER BY updatetime DESC,id DESC ';
    sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `
    let list = await Exec(sql);
    let peos = [];
    let invits = [];
    if (list && list.length) {
      let codestr = _.uniq(_.compact(_.pluck(list, 'pcode'))).join(',');
      let execsql = 'SELECT code,nickname,name,name_father,position,age,grender,education,level,avator,is_father,marital_status,invitcode,identity FROM hzz_peoples WHERE CODE IN (' + codestr + ')';
      peos = await Exec(execsql);
    }
    if (peos && peos.length) {
      let codestr2 = _.uniq(_.compact(_.pluck(peos, 'invitcode')));
      let inviter = _.filter(peos, (x) => {
        return x.level == 9;
      })
      codestr2 = codestr2.concat(_.pluck(inviter, 'code'));
      if (codestr2 && codestr2.length) {
        let execsql2 = 'SELECT pcode,name,nickname,usertype,marital_status,position,education FROM hzz_inviterhistories WHERE PCODE IN (' + codestr2.join(',') + ')';
        invits = await Exec(execsql2);
      }
    }
    list = _.map(list, function (item) {
      let pdata = _.find(peos, function (po) {
        return po.code == item.pcode;
      })
      if (pdata) {
        if(item.num){
          pdata.nickname +="【"+item.num+"】";
        }
        
        pdata.name = pdata.is_father ? pdata.name_father : (pdata.name ? pdata.name : pdata.name_father);
        delete pdata.is_father;
        delete pdata.name_father;
        pdata.invitername = '';
        let pdata2 = _.find(invits, function (po) {
          return po.pcode == pdata.invitcode;
        })
        if (pdata2) {
          pdata.invitername = pdata2.nickname;
          pdata.usertype = pdata2.usertype == 0 ? '个人' : '企业';
          if (item.level == 9) {
            pdata.name = pdata2.name;
            pdata.marital_status = pdata2.marital_status;
            pdata.position = pdata2.position;
            pdata.education = pdata2.education;
          }
        }
      }
      item.pdata = pdata;
      item.createtime = formatDateTime(item.createtime);
      if (item.paytime) {
        item.paytime = formatDateTime(item.paytime);
      }
      return item;
    });

    let total = (await ExecGetOne(`select count(1) as total from hzz_orders where 1=1 ` + ffter)).total
    Exec_Count('hzz_orders', pcode ? { pcode: pcode } : null, null);
    let pagecount = Math.ceil(total / pagesize);
    return {
      code: 0,
      data: {
        list,
        total,
        pagenum,
        pagesize,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    logger.info('-----order--orderList--订单列表异常,', error)
    return {
      code: 1,
      msg: '请求异常，请联系客服'
    }
  }
}

async function orderUpdate(doc) {
  if (doc.id) {
    if (doc.signstatus == 1) {
      // 如果签到成功，则更新活动签到人数 true_num
      let actData = await ExecGetOne(`select * from hzz_actives Where id=${doc.activeid}`);
      if (actData) {
        let true_num = actData.true_num + 1;
        await Exec(`update hzz_actives set true_num=${true_num} where id = ${doc.activeid}`);
        logger.info('--------orderUpdate--------如果签到成功，则更新活动签到人数 true_num', doc);
      } else {
        logger.info('--------orderUpdate--------未找到活动', doc);
      }
    }
    if (doc.paystatus == 1) {
      // 如果支付成功，则更新活动报名人数
      let actData = await ExecGetOne(`select * from hzz_actives Where id=${doc.activeid}`);
      if (actData) {
        let sign_num = actData.sign_num + 1;
        await Exec(`update hzz_actives set sign_num=${sign_num} where id = ${doc.activeid}`);
        logger.info('--------orderUpdate--------如果签到成功，则更新活动签到人数 sign_num', doc);
      } else {
        logger.info('--------orderUpdate--------未找到活动', doc);
      }
    }
    await Update('hzz_orders', format(doc));
    return {
      code: 0,
      msg: '更新订单成功'
    }
  } else if (doc.ordercode) {
    let data = await QueryOne('hzz_orders', { ordercode: doc.ordercode });
    if (data) {
      if (doc.signstatus == 1) {
        // 如果签到成功，则更新活动签到人数 true_num
        let actData = await ExecGetOne(`select * from hzz_actives Where id=${doc.activeid}`);
        if (actData) {
          let true_num = actData.true_num + 1;
          await Exec(`update hzz_actives set true_num=${true_num} where id = ${doc.activeid}`);
          logger.info('--------orderUpdate--------如果签到成功，则更新活动签到人数 true_num', doc);
        } else {
          logger.info('--------orderUpdate--------未找到活动', doc);
        }
      }
      if (doc.paystatus == 1) {
        // 如果支付成功，则更新活动报名人数
        let actData = await ExecGetOne(`select * from hzz_actives Where id=${doc.activeid}`);
        if (actData) {
          let sign_num = actData.sign_num + 1;
          await Exec(`update hzz_actives set sign_num=${sign_num} where id = ${doc.activeid}`);
          logger.info('--------orderUpdate--------如果签到成功，则更新活动签到人数 sign_num', doc);
        } else {
          logger.info('--------orderUpdate--------未找到活动', doc);
        }
      }
      doc.id = data.id;
      await Update('hzz_orders', format(doc));
      return {
        code: 0,
        msg: '更新订单成功'
      }
    } else {
      return {
        code: 1,
        msg: '未匹配到订单，更新订单状态失败'
      }
    }
  } else {
    return {
      code: 1,
      msg: '参数缺失，更新订单状态失败'
    }
  }
}

async function orderQueryone(doc) {
  try {
    logger.info('---------orderQueryone---,', doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: '参数缺失[pcode]'
      }
    }
    if (!doc.activeid) {
      return {
        code: 1,
        msg: '参数缺失[activeid]'
      }
    }
    let result = {
      code: 0,
      data: {}
    };
    let data = await QueryOne('hzz_orders', { pcode: doc.pcode, activeid: doc.activeid });
    if (data && data.paystatus != 9) {
      result.data = data;
    } else {
      result.data = {
        paystatus: -1 // 未创建订单
      };
    }
    return result;
  } catch (error) {
    return {
      code: 1,
      msg: '请求异常，请联系客服'
    }
  }
}


// 报名接口
async function signUp(doc, ip) {
  try {
    logger.info('报名接口:singnUp---doc,', doc);
    // if (!doc.price) {
    //   return {
    //     code: 1,
    //     msg: '参数缺失[price]'
    //   }
    // } else 
    if (!doc.activeid) {
      return {
        code: 1,
        msg: '参数缺失[activeid]'
      }
    } else if (!doc.pcode) {
      return {
        code: 1,
        msg: '参数缺失[pcode]'
      }
    }
    let signData = await ExecGetOne(`select * from hzz_actives Where id=${doc.activeid}`);
    let peopleData = await QueryOne('hzz_peoples', { code: doc.pcode }, 'openid,online,is_father,isinviter,level,invitcode,grender');
    let orders = await Query('hzz_orders', { activeid: doc.activeid, auditstatus: 1 });
    if (orders && signData) {
      // 活动过期
      if(signData.block){
        return {
          code: 1,
          msg: '活动已结束，请关注其它活动！'
        }
      }
      // 总人数超限
      if (orders.length >= signData.person) {
        return {
          code: 1,
          msg: '报名失败，本次活动已满员，请关注下次活动！'
        }
      }
      // 男女人数超限
      let grender = peopleData.grender;
      let glist = _.filter(orders, function (x) {
        return x.grender == grender;
      });
      if (glist && glist.length == signData.person / 2) {
        return {
          code: 1,
          msg: `报名失败，本次活动${grender}性用户已满员，请关注下次活动！`
        }
      }
    }
    if (!peopleData) {
      return {
        code: 1,
        msg: '报名失败，未找到用户信息！'
      }
    } else {
      if (!peopleData.isinviter) {
        if (peopleData.online != 1) {
          return {
            code: 1,
            msg: '报名失败，请先编辑个人资料，经平台发布后方可报名！'
          }
        }
        if (peopleData.is_father) {
          return {
            code: 1,
            msg: '报名失败，必须征婚本人报名！'
          }
        }
      } else {
        if (peopleData.level == 9) {
          return {
            code: 1,
            msg: '报名失败，推荐人暂不能报名！'
          }
        }
      }
    }
    let ordercode = doc.ordercode;
    // 创建系统订单
    if (!ordercode) {

      if (!signData) {
        logger.info('报名接口:singnUp---报名失败，活动信息获取失败');
        return {
          code: 1,
          msg: '报名失败，活动信息获取失败！'
        }
      }
      let new_order = {
        pcode: doc.pcode,
        invitecode: peopleData.invitcode,
        grender: peopleData.grender,
        ordercode: MathCode(),
        activeid: signData.id,
        title: signData.title,
        tourl: signData.tourl,
        imgurl: signData.imgurl,
        price: signData.price,
        total_fee: signData.price * 100,
        paystatus: 0
      };
      logger.info('报名接口:singnUp---new_order', JSON.stringify(new_order));
      let orderData = await orderAdd(new_order);
      if (orderData.code) {
        return orderData;
      } else {
        ordercode = orderData.ordercode;
      }
    }
    return {
      code: 0,
      msg: '报名成功，等待平台审核！'
    };
  } catch (error) {
    logger.info('报名接口:singnUp---error,', error);
    return {
      code: 1,
      msg: '报名异常，请联系客服'
    }
  }
}
// 签到
async function signIn(doc) {
  try {
    logger.info('---签到--signIn,', doc)
    let nowtime = new Date().getTime();
    if (!doc.activeid) {
      return {
        code: 1,
        msg: '签到失败,activeid not found'
      }
    }
    if (!doc.pcode) {
      return {
        code: 1,
        msg: '签到失败,pcode not found'
      }
    }
    let orderData = await QueryOne('hzz_orders', { pcode: doc.pcode, activeid: doc.activeid,paystatus:1 });
    logger.info('---签到--signIn,orderData', orderData)
    if (orderData) {
      let signNUM = orderData.num;
      //if (orderData.paystatus == 1) {
        await updateHistory(orderData, { msg: '签到成功，请尽快入场!', datetime: new Date() }, 1);
        if (signNUM == 0) {
          signNUM = await getUserNum(orderData);// 获取签到码
        }
        //  推送本次活动全部异性给签到用户
        // await activeDone({code: doc.pcode, activeid: doc.activeid});
        // 已签到用户异性互推
        signSendUser(doc.activeid);
        logger.info('---签到--signIn,签到成功，请尽快入场,signNUM:' + signNUM)
        //发送订阅消息
        let send_data = {
          "first": {
            "value": "您好，您的业务有新进展!",
            "color": "#173177"
          },
          "keyword1": {
            "value": "活动签到",
            "color": "#173177"
          },
          "keyword2": {
            "value": `签到成功，您的签到码:【 ${signNUM} 】！`,
            "color": "#6aa84f"
          },
          "remark": {
            "value": "欢迎您的到来，请尽快入场！",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing1": {
            "value": "活动签到"
          },
          "thing3": {
            "value": `签到成功，您的签到码:【 ${signNUM} 】！`
          },
          "thing4": {
            "value": "欢迎您的到来，请尽快入场！"
          },
          "time2": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('daeay_tmpid', send_data, orderData.pcode, "pages/index/index", send_data_red);
        // 根据签到时间，早于活动开始时间，则发起微信退款，退掉报名时缴纳的守时费
        if(orderData.backstatus!='SUCCESS' ){
          let activeData = await ExecGetOne(`select * from hzz_actives Where id=${doc.activeid}`);
          logger.info('----singnIn---签到校验是否退款？nowtime：', nowtime)
          logger.info('----singnIn---签到校验是否退款？date_begin：', new Date(activeData.date_begin).getTime())
          if(nowtime <= new Date(activeData.date_begin).getTime() && orderData.paystatus ==1 && orderData.signstatus==1 && (orderData.backstatus==null || orderData.backstatus=="404")){
            let rparmas={
              ordercode: orderData.ordercode, 
              refund_money: activeData.refund* 100, 
              origin_money: orderData.total_fee
            };
            logger.info('----singnIn---正在退款---：', JSON.stringify(rparmas))
            await refunds(rparmas);
          }
        }
          
        return {
          code: 0,
          msg: '签到成功，请尽快入场！签到码：' + signNUM
        }
      // } else {
      //   logger.info('---签到--signIn,签到失败，您报名的订单尚未支付成功!!!')
      //   updateHistory(orderData, { msg: '签到失败，您报名的订单尚未支付成功!!!', datetime: new Date() }, 2);
      //   return {
      //     code: 1,
      //     msg: '签到失败，您报名的订单尚未支付成功！'
      //   }
      // }
    } else {
      return {
        code: 1,
        msg: '签到失败，请联系现场工作人员报名！'
      }
    }
  } catch (error) {
    logger.info('----singnIn---签到异常!!!,', error)
    return {
      code: 1,
      msg: '签到异常，请联系客服'
    }
  }
}
// 更新签到记录
async function updateHistory(orderData, newRemark, signstatus) {
  let remarks = [];
  if (orderData.remarks) {
    remarks = JSON.parse(orderData.remarks);
  }
  remarks.push(newRemark);
  let doc = {
    id: orderData.id,
    ordercode: orderData.ordercode,
    activeid: orderData.activeid,
    signstatus: signstatus,
    signtime: new Date(),
    remarks: JSON.stringify(remarks)
  };
  logger.info('-------updateHistory------', doc);
  let resdata = await orderUpdate(doc);
  logger.info('-------updateHistory------', resdata);
}
// 获取签到编号
async function getUserNum(orderData) {
  let activeData = await ExecGetOne(`select * from hzz_actives Where id=${orderData.activeid}`);
  //总人数
  let peonum = activeData.person;
  // 编号数组
  let numarr1 = []; // 男性编号
  let numarr2 = []; // 女性编号
  let numarr = [];
  let usernum = 0;
  for (let index = 1; index < peonum; index++) {
    if (index % 2 == 0) {
      numarr2.push(index);
    } else {
      numarr1.push(index);
    }
  }
  let orderList = await Exec(`select * from hzz_orders where activeid = ${orderData.activeid} and num<>0`);
  if (orderData.grender == '男') {
    numarr = numarr1;
  } else {
    numarr = numarr2;
  }
  for (let i = 0; i < numarr.length; i++) {
    const num = numarr[i];
    let issend = _.find(orderList, function (x) {
      return x.num == num;
    });
    if (!issend) {
      usernum = num;
      // 更新用户签到码
      await Exec(`update  hzz_orders set num=${usernum} where id = ${orderData.id} `);
      break;
    }
  }
  return usernum;
}
async function order_edit(doc) {
  try {
    if (!doc.id) {
      return {
        code: 1,
        msg: '缺失参数[id]'
      }
    }
    let upOBJ = {
      id: doc.id,
    };
    if (doc.paystatus || doc.paystatus == 0) {
      upOBJ.paystatus = doc.paystatus;
    }
    if (doc.auditstatus || doc.auditstatus == 0) {
      upOBJ.auditstatus = doc.auditstatus;
    }
    if (doc.signstatus || doc.signstatus == 0) {
      upOBJ.signstatus = doc.signstatus;
    }
    // 审核成功发送订阅消息
    let old= await QueryOne('hzz_orders',{id: doc.id});
    await Update('hzz_orders', format(upOBJ));
    if(old.auditstatus==0){
      if(doc.auditstatus ==1){
          //发送订阅消息
          let send_data = {
            "first": {
              "value": "您提交的活动报名申请已审核!",
              "color": "#173177"
            },
            "keyword1": {
              "value": "平台审核通过!",
              "color": "#59B10"
            },
            "keyword2": {
              "value": formatDateTime(new Date()),
              "color": "#173177"
            },
            "remark": {
              "value": "请前往'我的-线下活动',及时完成支付!",
              "color": "#173177"
            }
          };
          let send_data_red = {
            "thing2": {
              "value": "您提交的活动报名申请已通过!"
            },
            "time1": {
              "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
            }
          };
          sendMsg('recomreview_tmpid', send_data, old.pcode, "pages/myInfo/myInfo",send_data_red);
        }else if(doc.auditstatus ==2){
          //发送订阅消息
          let send_data = {
            "first": {
              "value": "您提交的活动报名申请已审核!",
              "color": "#173177"
            },
            "keyword1": {
              "value": "平台审核不通过!",
              "color": "#70808"
            },
            "keyword2": {
              "value": formatDateTime(new Date()),
              "color": "#173177"
            },
            "remark": {
              "value": "很抱歉，本次活动报名人数已满，请关注下次活动!",
              "color": "#173177"
            }
          };
          let send_data_red = {
            "thing2": {
              "value": "您提交的活动报名申请未通过!"
            },
            "time1": {
              "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
            }
          };
          sendMsg('recomreview_tmpid', send_data, old.pcode, "pages/myInfo/myInfo",send_data_red);
        }
    }
    return {
      code: 0,
      msg: '修改成功'
    }
  } catch (err) {
    logger.info('order_edit', err);
    return {
      code: 1,
      msg: '修改异常，请联系管理员'
    }
  }
}
async function orderById(doc) {
  try {
    if (!doc.id) {
      return {
        code: 1,
        msg: '缺失参数[id]'
      }
    }
    let data = await ExecGetOne(`select * from hzz_orders where id=${doc.id}`);
    return {
      code: 0,
      data: data,
      msg: '获取成功'
    }
  } catch (err) {
    return {
      code: 1,
      msg: '获取异常，请联系管理员'
    }
  }
}
let userlevel = {
  0: '游客',
  1: '用户',
  9: '推荐人',
  19: '用户/推荐人'
};
let paystatus_val = {
  0: '未支付',
  1: '已支付',
  9: '已退款'
};
let signstatus_val = {
  0: '未签到',
  1: '已签到',
  9: '签到失败'
};
let auditstatus_val = {
  0: '待审核',
  1: '已通过',
  2: '已拒绝'
};
let usertype_val = {
  0: '个人',
  1: '企业'
};
// 导出列表
const orderExport = async function (doc) {
  try {
    logger.info('----orderExport--,', doc)
    let { Filter } = doc;
    let sql = `SELECT * FROM hzz_orders Where 1=1 `;
    if (Filter) {
      let fter = ' where 1=1 ';
      let { name, grender, level, paystatus } = Filter;
      if (name) {
        fter += ` AND (nickname like '%${name}%' or name like '%${name}%' or name_father like '%${name}%')`;
      }
      if (grender) {
        fter += ` AND grender = '${grender}'`;
      }
      if (level) {
        fter += ` AND level=${level}`;
      }
      let peol = await Exec(`select code from hzz_peoples ` + fter);
      let pcodel = _.uniq(_.compact(_.pluck(peol, 'code')));
      if (pcodel && pcodel.length) {
        sql += ` AND pcode IN(${pcodel.join(',')})`
      }
      if ((paystatus || paystatus == 0) && paystatus != '') {
        sql += ` AND paystatus=${paystatus}`;
      }
    }
    sql += ' ORDER BY updatetime DESC,id DESC ';
    let list = await Exec(sql);
    let peos = [];
    let invits = [];
    if (list && list.length) {
      let codestr = _.uniq(_.compact(_.pluck(list, 'pcode'))).join(',');
      let execsql = 'SELECT code,nickname,name,name_father,age,grender,education,level,avator,is_father,marital_status,invitcode,identity,position FROM hzz_peoples WHERE CODE IN (' + codestr + ')';
      peos = await Exec(execsql);
    }
    if (peos && peos.length) {
      let codestr2 = _.uniq(_.compact(_.pluck(peos, 'invitcode')));
      let inviter = _.filter(peos, (x) => {
        return x.level == 9;
      })
      codestr2 = codestr2.concat(_.pluck(inviter, 'code'));
      if (codestr2 && codestr2.length) {
        let execsql2 = 'SELECT pcode,name,nickname,usertype,marital_status,position,education FROM hzz_inviterhistories WHERE PCODE IN (' + codestr2.join(',') + ')';
        invits = await Exec(execsql2);
      }
    }
    let list_xlsx = [['序号', '用户昵称', '真实姓名', '性别', '年龄', '婚姻状况', '学历', '职业', '用户级别', '推荐人', '推荐人类型', '活动标题', '订单金额', '审核状态', '支付状态', '签到状态', '签到时间', '报名时间']];

    let n = 1;
    list = _.map(list, function (item) {
      let pdata = _.find(peos, function (po) {
        return po.code == item.pcode;
      })
      if (pdata) {
        pdata.name = pdata.is_father ? pdata.name_father : (pdata.name ? pdata.name : pdata.name_father);
        delete pdata.is_father;
        delete pdata.name_father;
        pdata.invitername = '';
        let pdata2 = _.find(invits, function (po) {
          return po.pcode == pdata.invitcode;
        })
        if (pdata2) {
          pdata.invitername = pdata2.nickname;
          pdata.usertype = pdata2.usertype;
          if (item.level == 9) {
            pdata.name = pdata2.name;
            pdata.marital_status = pdata2.marital_status;
            pdata.position = pdata2.position;
            pdata.education = pdata2.education;
          }
        }
      }
      item.pdata = pdata;
      item.createtime = formatDateTime(item.createtime);
      item.signtime = formatDateTime(item.signtime);
      if (item.paytime) {
        item.paytime = formatDateTime(item.paytime);
      }
      list_xlsx.push([n, item.pdata.nickname, item.pdata.name, item.pdata.grender, item.pdata.age, item.pdata.marital_status, item.pdata.education, item.pdata.position, userlevel[item.pdata.level], item.pdata.invitername, usertype_val[item.pdata.usertype], item.title, item.price, auditstatus_val[item.auditstatus], paystatus_val[item.paystatus], signstatus_val[item.signstatus], item.signtime, item.createtime]);
      n++;
    });

    let portList = [
      {
        name: "订单明细",
        data: list_xlsx
      }
    ]
    return await exportParse(portList, '订单明细');
  } catch (error) {
    logger.info('----error--,', error)
    return {
      code: 1,
      msg: '导出失败'
    }
  }
}
let list = [
  { "序号": 1, "用户昵称": " lee", "真实姓名": "李先武", "性别": "男", "年龄": 34, "婚姻状况": "未婚", "学历": "本科", "职业": "公务员", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-18 18:24" },
  { "序号": 2, "用户昵称": "那个他", "真实姓名": "殷德齐", "性别": "男", "年龄": 28, "婚姻状况": "未婚", "学历": "大专", "职业": "私企", "用户级别": "用户", "推荐人": "佘老师", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-18 17:20" },
  { "序号": 3, "用户昵称": "神经蛙", "真实姓名": "傅钰琪", "性别": "女", "年龄": 27, "婚姻状况": "未婚", "学历": "本科", "职业": "自由职业", "用户级别": "用户", "推荐人": "佘老师", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-18 17:55" },
  { "序号": 4, "用户昵称": "Where", "真实姓名": "李伟", "性别": "男", "年龄": 33, "婚姻状况": "未婚", "学历": "大专", "职业": "其它", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-19 10:53" },
  { "序号": 5, "用户昵称": "烟雨潇潇", "真实姓名": "何华", "性别": "男", "年龄": 34, "婚姻状况": "未婚", "学历": "本科", "职业": "IT工程师", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-19 09:21" },
  { "序号": 6, "用户昵称": "婕婕", "真实姓名": "李陈娇", "性别": "女", "年龄": 36, "婚姻状况": "未婚", "学历": "本科", "职业": "上市公司", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-18 22:41" },
  { "序号": 7, "用户昵称": "Rina", "真实姓名": "郑玉梅", "性别": "女", "年龄": 35, "婚姻状况": "未婚", "学历": "本科", "职业": "私企", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已退款", "报名时间": "2022-11-16 14:44" },
  { "序号": 8, "用户昵称": "mmpooh", "真实姓名": "张旻", "性别": "女", "年龄": 33, "婚姻状况": "未婚", "学历": "硕士", "职业": "技术员", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-18 21:43" },
  { "序号": 9, "用户昵称": "阿光", "真实姓名": "廖晗光", "性别": "男", "年龄": 22, "婚姻状况": "未婚", "学历": "本科", "职业": "自由职业", "用户级别": "用户", "推荐人": "佘老师", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-18 17:26" },
  { "序号": 10, "用户昵称": "小陌墨", "真实姓名": "吴燕飞", "性别": "女", "年龄": 32, "婚姻状况": "未婚", "学历": "本科", "职业": "互联网", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-18 17:03" },
  { "序号": 11, "用户昵称": "Bluesky", "真实姓名": "刘锦", "性别": "男", "年龄": 36, "婚姻状况": "未婚", "学历": "本科", "职业": "私企", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-18 15:32" },
  { "序号": 12, "用户昵称": "雪梨", "真实姓名": "谢青", "性别": "女", "年龄": 35, "婚姻状况": "未婚", "学历": "硕士", "职业": "金融", "用户级别": "用户", "推荐人": "孟姐", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-18 14:41" },
  { "序号": 13, "用户昵称": "qat", "真实姓名": "千安泰", "性别": "男", "年龄": 33, "婚姻状况": "未婚", "学历": "本科", "职业": "私企", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-18 13:14" },
  { "序号": 14, "用户昵称": "安琪", "真实姓名": "谭安琪", "性别": "女", "年龄": 31, "婚姻状况": "未婚", "学历": "硕士", "职业": "国企", "用户级别": "推荐人", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-18 14:20" },
  { "序号": 15, "用户昵称": "Jerry.wang", "真实姓名": "王丰收", "性别": "男", "年龄": 39, "婚姻状况": "未婚", "学历": "本科", "职业": "自由职业", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-18 12:58" },
  { "序号": 16, "用户昵称": "L", "真实姓名": "刘世蒙", "性别": "男", "年龄": 27, "婚姻状况": "未婚", "学历": "本科", "职业": "自由职业", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-18 11:18" },
  { "序号": 17, "用户昵称": "豆号461178", "真实姓名": "何维妮", "性别": "女", "年龄": 26, "婚姻状况": "未婚", "学历": "本科", "职业": "自由职业", "用户级别": "推荐人", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-18 11:07" },
  { "序号": 18, "用户昵称": "洪华", "真实姓名": "谭洪华", "性别": "男", "年龄": 42, "婚姻状况": "离异", "学历": "硕士", "职业": "董事长", "用户级别": "用户/推荐人", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-18 09:43" },
  { "序号": 19, "用户昵称": "HUAWEI搬砖工", "真实姓名": "梁明达", "性别": "男", "年龄": 29, "婚姻状况": "未婚", "学历": "本科", "职业": "私企", "用户级别": "用户", "推荐人": "孟姐", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-18 09:38" },
  { "序号": 20, "用户昵称": "逗丁", "真实姓名": "欧国斌", "性别": "男", "年龄": 33, "婚姻状况": "未婚", "学历": "本科", "职业": "IT工程师", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "D": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-18 09:27" },
  { "序号": 21, "用户昵称": "Polo", "真实姓名": "朱海燕", "性别": "女", "年龄": 35, "婚姻状况": "未婚", "学历": "硕士", "职业": "教师", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 15:51" },
  { "序号": 22, "用户昵称": "Zoe", "真实姓名": "高凌云", "性别": "女", "年龄": 31, "婚姻状况": "离异无孩", "学历": "硕士", "职业": "事业单位", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-17 19:02" },
  { "序号": 23, "用户昵称": "玉玲", "真实姓名": "彭玉玲", "性别": "女", "年龄": 32, "婚姻状况": "未婚", "学历": "本科", "职业": "私企", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-17 17:35" },
  { "序号": 24, "用户昵称": "李鲍勃", "真实姓名": "李梦一", "性别": "男", "年龄": 31, "婚姻状况": "未婚", "学历": "硕士", "职业": "销售", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-17 17:33" },
  { "序号": 25, "用户昵称": "吾叶轻飘", "真实姓名": "彭斌", "性别": "男", "年龄": 36, "婚姻状况": "离异无孩", "学历": "本科", "职业": "教师", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-17 17:24" },
  { "序号": 26, "用户昵称": "一朵向日葵", "真实姓名": "艾聪", "性别": "女", "年龄": 28, "婚姻状况": "未婚", "学历": "硕士", "职业": "自由职业", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-17 14:51" },
  { "序号": 27, "用户昵称": "浩犇", "真实姓名": "徐燕浩", "性别": "男", "年龄": 25, "婚姻状况": "未婚", "学历": "本科", "职业": "自由职业", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-17 09:11" },
  { "序号": 28, "用户昵称": "平常心", "真实姓名": "梁状", "性别": "女", "年龄": 30, "婚姻状况": "未婚", "学历": "本科", "职业": "IT工程师", "用户级别": "用户", "推荐人": "刘美纯", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-17 12:08" },
  { "序号": 29, "用户昵称": "田", "真实姓名": "田能源", "性别": "男", "年龄": 29, "婚姻状况": "未婚", "学历": "硕士", "职业": "上市公司", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 18:02" },
  { "序号": 30, "用户昵称": "KKlove", "真实姓名": "游慧", "性别": "女", "年龄": 32, "婚姻状况": "未婚", "学历": "本科", "职业": "英文技术支持", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已退款", "报名时间": "2022-11-16 18:45" },
  { "序号": 31, "用户昵称": "Jenn", "真实姓名": "刘迪", "性别": "女", "年龄": 32, "婚姻状况": "未婚", "学历": "硕士", "职业": "金融", "用户级别": "用户", "推荐人": "郑竹子", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 18:00" },
  { "序号": 32, "用户昵称": "6到飞起", "真实姓名": "刘日平", "性别": "男", "年龄": 32, "婚姻状况": "未婚", "学历": "本科", "职业": "教师", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 20:21" },
  { "序号": 33, "用户昵称": "阿星", "真实姓名": "龙欣", "性别": "男", "年龄": 27, "婚姻状况": "未婚", "学历": "本科", "职业": "政府部门（非公务员）", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-16 19:37" },
  { "序号": 34, "用户昵称": "鹏城居士", "真实姓名": "许海林", "性别": "男", "年龄": 35, "婚姻状况": "离异不带孩", "学历": "硕士", "职业": "公务员", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 19:16" },
  { "序号": 35, "用户昵称": "智能丰收", "真实姓名": "张祖收", "性别": "男", "年龄": 33, "婚姻状况": "未婚", "学历": "本科", "职业": "国企", "用户级别": "用户", "推荐人": "何维妮", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "未支付", "报名时间": "2022-11-16 19:05" },
  { "序号": 36, "用户昵称": "半江南", "真实姓名": "穆二强", "性别": "男", "年龄": 41, "婚姻状况": "离异无孩", "学历": "硕士", "职业": "国企", "用户级别": "用户", "推荐人": "孟姐", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 14:59" },
  { "序号": 37, "用户昵称": "阿九", "真实姓名": "谭雨晴", "性别": "女", "年龄": 25, "婚姻状况": "未婚", "学历": "本科", "职业": "产品测试工程师", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 12:48" },
  { "序号": 38, "用户昵称": "叶子", "真实姓名": "叶思媛", "性别": "女", "年龄": 30, "婚姻状况": "未婚", "学历": "本科", "职业": "财务", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 12:24" },
  { "序号": 39, "用户昵称": "晓婕", "真实姓名": "胡晓婕", "性别": "女", "年龄": 31, "婚姻状况": "未婚", "学历": "本科", "职业": "自由职业", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 12:02" },
  { "序号": 40, "用户昵称": "欧阳", "真实姓名": "阳超前", "性别": "男", "年龄": 31, "婚姻状况": "未婚", "学历": "本科", "职业": "CEO", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 12:13" },
  { "序号": 41, "用户昵称": "闫", "真实姓名": "闫照庆", "性别": "男", "年龄": 31, "婚姻状况": "未婚", "学历": "本科", "职业": "上市公司", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 11:52" },
  { "序号": 42, "用户昵称": "terry", "真实姓名": "文斐达", "性别": "男", "年龄": 26, "婚姻状况": "未婚", "学历": "本科", "职业": "央企", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 09:29" },
  { "序号": 43, "用户昵称": "红豆用户962814", "真实姓名": "王文明", "性别": "男", "年龄": 35, "婚姻状况": "未婚", "学历": "本科", "职业": "教师", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-16 08:37" },
  { "序号": 44, "用户昵称": "晚棠", "真实姓名": "赵子沫", "性别": "女", "年龄": 26, "婚姻状况": "未婚", "学历": "硕士", "职业": "金融", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-15 17:08" },
  { "序号": 45, "用户昵称": "进哥无敌", "真实姓名": "董作进", "性别": "男", "年龄": 30, "婚姻状况": "未婚", "学历": "硕士", "职业": "", "用户级别": "用户/推荐人", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-15 09:15" },
  { "序号": 46, "用户昵称": "AstoriaMT", "真实姓名": "余梦婷", "性别": "女", "年龄": 27, "婚姻状况": "未婚", "学历": "硕士", "职业": "事业单位", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-15 16:22" },
  { "序号": 47, "用户昵称": "小张", "真实姓名": "张钰", "性别": "女", "年龄": 27, "婚姻状况": "未婚", "学历": "本科", "职业": "金融", "用户级别": "用户", "推荐人": "中诚达评估公司副董事长", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-15 17:05" },
  { "序号": 48, "用户昵称": "kevin", "真实姓名": "王淇雲", "性别": "男", "年龄": 27, "婚姻状况": "未婚", "学历": "硕士", "职业": "公务员", "用户级别": "用户", "推荐人": "勤快乐", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-15 16:46" },
  { "序号": 49, "用户昵称": "Eacy", "真实姓名": "颜兰馨", "性别": "女", "年龄": 26, "婚姻状况": "未婚", "学历": "硕士", "职业": "教师", "用户级别": "用户", "推荐人": "文祖良", "推荐人类型": "个人", "活动标题": "1120·鹏城之约", "订单金额": 99, "支付状态": "已支付", "报名时间": "2022-11-15 21:43" },
];
async function insertOrder() {
  let paystatus_val = {
    '未支付': 0,
    '已支付': 1,
    '已退款': 9
  };
  for (let index = 0; index < list.length; index++) {
    const item = list[index];
    let obj = {

    };
    let sql = `select code from hzz_peoples where nickname='${item['用户昵称']}' or name='${item['真实姓名']}' or name_father ='${item['真实姓名']}'`;

    let peo = await ExecGetOne(sql);
    if (!peo) {
      console.log('not found,', sql)
      continue;
    }
    obj.pcode = peo.code;
    obj.ordercode = MathCode();
    let active = await QueryOne('hzz_actives', { id: 1 });
    obj.activeid = 1;
    obj.title = item['活动标题'];
    obj.tourl = active.tourl;
    obj.imgurl = active.imgurl;
    obj.price = active.price;
    obj.total_fee = active.price * 100;
    obj.paystatus = paystatus_val[item['支付状态']];
    obj.signstatus = 0;
    obj.createtime = new Date(item['报名时间']);
    obj.updatetime = new Date(item['报名时间']);
    obj.ordertype = '线下活动';
    Add('hzz_orders', obj);
  }
}

async function signAll(activeid) {
  let list = await Exec(`select * from hzz_orders where activeid=${activeid} and paystatus<>9`);
  for (let index = 0; index < list.length; index++) {
    const item = list[index];
    //  推送本次活动全部异性给签到用户
    await activeDone({ code: item.pcode, activeid: item.activeid });
    await Update('hzz_orders', { id: item.id, signstatus: 1 });
    console.log('---系统自动签到--signIn,签到成功，请尽快入场', item.pcode)
  }
}
async function initInvitcode() {
  let list = await Exec(`select * from hzz_orders`);
  for (let index = 0; index < list.length; index++) {
    let item = list[index];
    let peoData = await QueryOne('hzz_peoples', { code: item.pcode }, 'grender');
    if (peoData) {
      await Exec(`update hzz_orders set grender='${peoData.grender}' where id= ${item.id}`);
    }
  }
}


async function updateOrderInfo(ordercode, info){
  let order = await QueryOne('hzz_orders', {ordercode: ordercode});
  if(order){
      info.id= order.id;
      await Update('hzz_orders',info);
      if(info.paystatus ==1){
          //发送订阅消息
          let send_data = {
            "first": {
              "value": "您好，您的业务有新进展!",
              "color": "#173177"
            },
            "keyword1": {
              "value": "活动费用支付",
              "color": "#173177"
            },
            "keyword2": {
              "value": `您报名的活动费用，支付成功!`,
              "color": "#6aa84f"
            },
            "remark": {
              "value": "请于活动当天准时到达现场完成签到，祝您早日脱单!",
              "color": "#173177"
            }
          };
          let send_data_red = {
            "thing1": {
              "value": "活动费用支付"
            },
            "thing3": {
              "value": `您报名的活动费用，支付成功!`
            },
            "thing4": {
              "value": "请于活动当天准时到达现场完成签到，祝您早日脱单!"
            },
            "time2": {
              "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
            }
          };
          sendMsg('daeay_tmpid', send_data, order.pcode, "pages/index/index", send_data_red);
      }
  }
}
async function sendMsgError(ordercode){
  let order = await QueryOne('hzz_orders', {ordercode: ordercode});
  if(order){
      //发送订阅消息
      let send_data = {
        "first": {
          "value": "您好，您的业务有新进展!",
          "color": "#173177"
        },
        "keyword1": {
          "value": "活动费用支付",
          "color": "#173177"
        },
        "keyword2": {
          "value": `您报名的活动费用，支付失败!`,
          "color": "#ff3300"
        },
        "remark": {
          "value": "活动费用支付失败，请尝试重新支付!",
          "color": "#173177"
        }
      };
      let send_data_red = {
        "thing1": {
          "value": "活动费用支付"
        },
        "thing3": {
          "value": `您报名的活动费用，支付失败!`
        },
        "thing4": {
          "value": "活动费用支付失败，请尝试重新支付!"
        },
        "time2": {
          "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
        }
      };
      sendMsg('daeay_tmpid', send_data, order.pcode, "pages/index/index", send_data_red);
  }
}
async function sendRefondMsgError(ordercode){
  let order = await QueryOne('hzz_orders', {ordercode: ordercode});
  if(order){
      //发送订阅消息
      let send_data = {
        "first": {
          "value": "您好，您的业务有新进展!",
          "color": "#173177"
        },
        "keyword1": {
          "value": "活动守时费用退款",
          "color": "#173177"
        },
        "keyword2": {
          "value": `您报名的活动守时费用，退款失败!`,
          "color": "#ff3300"
        },
        "remark": {
          "value": "活动守时费用退款失败，请联系现场工作人员!",
          "color": "#173177"
        }
      };
      let send_data_red = {
        "thing1": {
          "value": "活动费用退款"
        },
        "thing3": {
          "value": `您报名的活动守时费用，退款失败!`
        },
        "thing4": {
          "value": "活动守时费用退款失败，请联系现场工作人员!"
        },
        "time2": {
          "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
        }
      };
      sendMsg('daeay_tmpid', send_data, order.pcode, "pages/index/index", send_data_red);
  }
}
async function order_notice(body) {
  try {
      logger.info('-------order_notice-----body,', body)
      // 解密回调信息
      const result = await decodeData(body.resource);
      logger.info('-------order_notice-----result,', result)
      // 拿到订单号
      let { out_trade_no } = result;
      if (result && result.trade_state == 'SUCCESS') {
          logger.info('-------order_notice-----支付成功之后需要进行的业务逻辑,')
          // 支付成功之后需要进行的业务逻辑
          // 更新订单支付状态
          let upobj = {
              paystatus: 1,
              paytime: new Date(),
              paytype: "JSAPI",
              order_info: JSON.stringify(result)
          };
          // 更新订单信息
          updateOrderInfo(out_trade_no, upobj);
      } else {
          logger.info('-------order_notice-----支付失败之后需要进行的业务逻辑')
          sendMsgError(out_trade_no);
      }
  } catch (error) {
      logger.info('-------order_notice-----error，', error)
  }
}
async function order_back(body) {
  try {
      logger.info('-------order_back-----body,', body)
      // 解密回调信息
      const result = await decodeData(body.resource);
      logger.info('-------order_back-----result,', result)
      // 拿到订单号
      let { out_trade_no,refund_status,success_time } = result;
      if (refund_status == 'SUCCESS') {
          logger.info('-------order_back-----退款成功之后需要进行的业务逻辑,')
          // 退款成功之后需要进行的业务逻辑
          // 更新订单退款状态
          await Exec(`update hzz_orders set backstatus=?, backtime=? where ordercode= ?`,[refund_status, success_time, out_trade_no]);
      } else {
          logger.info('-------order_back-----支付失败之后需要进行的业务逻辑')
          sendRefondMsgError(out_trade_no);
      }
  } catch (error) {
      logger.info('-------order_back-----error，', error)
  }
}

module.exports = {
  orderAdd,
  orderUpdate,
  orderList,
  orderQueryone,
  signUp,
  signIn,
  order_edit,
  orderById,
  orderExport,
  insertOrder,
  signAll,
  initInvitcode,
  updateOrderInfo,
  sendMsgError,
  order_notice,
  order_back
}